﻿//一.定义全局变量命名空间
//只创建一个全局变量，并定义该变量为当前应用容器，把其他全局变量追加在该命名空间下

//var a = {
//    defaultParam: {
//        '参数1': '初始值',
//        '参数2': 0,
//        '参数3': true
//    },
//    b: function (param) {
//        if (!param) param = {};
//        if (typeof param['参数1'] === 'undefined') {
//            param['参数1'] = a.defaultParam['参数1']
//        }
//        if (typeof param['参数2'] === 'undefined') {
//            param['参数2'] = a.defaultParam['参数2']
//        }
//        if (typeof param['参数3'] === 'undefined') {
//            param['参数3'] = a.defaultParam['参数3']
//        }
//        alert(param['参数1']);
//        alert(param['参数2']);
//        //alert(param['参数3']);
//    }
//};
//namespaces.lay = {
//    school_work: "study",
//    family_work: "we are"
//};

var layer, laypage, form, JsonData = {}, EditSingle = 0, base = "./handler/", index = 0, _name = null;;
var namespaces = namespaces || {};
layui.config({
    base: 'plugins/layui/modules/'
});

(function($) {
    //定义一些默认参数
    var options = {
        'Ctable': 'dynamic-table',
        'get_url': null,
        'Array_id': 0,
        'container': 'main',
        'row': 0,
        'column': 0,
        'Array_title': null,
        'table': null,
        'pagecount': 0,
        'editMode': 'edit',
        'rowCount': 0,
        'rowNum': 10,
        'dialogID':0,
        'curr':1,
        'original_row': -1,
        'tr_count': 0,
        'curr_num': 0,
        'select_row': 10,
        'select_item': '*',
        'KindEditor': null,
        'selectImage': null,
        'id_selector': function (selector) {
            return document.getElementById(selector);
        }
    }
    //定义一些api
    var plugin_api = {
        init: function (param) {
            if (!param) param = {};
            if (typeof param['Ctable'] !== 'undefined') { options.get_url = param['Ctable']; }
            if (typeof param['get_url'] !== 'undefined') { options.get_url = param['get_url']; }
            if (typeof param['page_url'] !== 'undefined') { options.page_url = param['page_url']; }
            if (typeof param['Array_id'] !== 'undefined') { options.Array_id = param['Array_id']; }
            if (typeof param['container'] !== 'undefined') { options.container = param['container']; }
            if (typeof param['row'] !== 'undefined') { options.row = param['row']; }
            if (typeof param['column'] !== 'undefined') { options.column = param['column']; }
            if (typeof param['Array_title'] !== 'undefined') { options.Array_title = param['Array_title']; }
            if (typeof param['table'] !== 'undefined') { options.table = param['table']; }
            if (typeof param['pagecount'] !== 'undefined') { options.pagecount = param['pagecount']; }
            if (typeof param['rowCount'] !== 'undefined') { options.rowCount = param['rowCount']; }
            if (typeof param['rowNum'] !== 'undefined') { options.rowNum = param['rowNum']; }
            if (typeof param['editMode'] !== 'undefined') { options.editMode = param['editMode']; }
            if (typeof param['curr'] !== 'undefined') { options.curr = param['curr']; }
            if (typeof param['tr_count'] !== 'undefined') { options.tr_count = param['tr_count']; }
            if (typeof param['curr_num'] !== 'undefined') { options.curr_num = param['curr_num']; }
            if (typeof param['select_row'] !== 'undefined') { options.select_row = param['select_row']; }
            if (typeof param['select_item'] !== 'undefined') { options.select_item = param['select_item']; }
            plugin_api.GetValue();
        },
        GetValue: function () {
            options.select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : options.rowNum;
            var sql1, sql2;
            if (options.curr == 1) {
                sql1 = "select SQL_CALC_FOUND_ROWS " + options.Array_id + " from " + options.table + " order by time DESC" + " limit 0," + options.curr * options.select_row + ";";
                sql2 = "SELECT FOUND_ROWS();";
            }
            else {
                sql1 = "select SQL_CALC_FOUND_ROWS " + options.Array_id + " from " + options.table + " order by time DESC" + " limit " + (options.curr - 1) * options.select_row + "," + options.select_row + ";";
                sql2 = "SELECT FOUND_ROWS();";
            }
            $.ajax({
                type: 'POST',
                url: base + options.get_url + ".ashx?t=" + Math.random().toString(),
                data: {
                    "sql1": sql1,
                    "sql2": sql2,
                },
                dataType: 'json',
                cache: false,
                beforeSend: function () {
                    //加载中
                    //options.dialogID = layer.load(1, {
                    //    shade: [0.1, '#fff'] //0.1透明度的白色背景
                    //});
                },
                success: function (data, textStatus) {
                    //parent.layer.msg('加载完毕！', { icon: 1, time: 1000 });
                    layer.close(options.dialogID)
                    var Array_item = [];
                    var c = 0;
                    var i = 0;
                    var jsonObj;
                    var jsonData;
                    $("#" + options.container).empty();
                    $("#" + options.container).append('<table id="' + options.Ctable + '" class="layui-table site-table table-hover admin-table"></table>')
                    $("#" + options.Ctable).append("<thead id='title'></thead>")
                    $("#title").append("<tr id='line'></tr>");
                    //表头
                    for (c; c < options.column; c++) {
                        if (c == 0) { $("#line").append("<th  style='text-align:center;'><input type='checkbox' lay-filter='selected-all' lay-skin='primary' id='selected-all' Dataid='" + options.Array_id[0] + "'>"); }//<input type='checkbox' id='selected-all' Dataid='"+options.Array_id[0]+"'/> 
                        else { $("#line").append("<th  style='text-align:center;'>" + options.Array_title[c - 1] + "</th>"); }
                    }
                    $("#" + options.Ctable).append("<tbody id='cont'></tbody")
                    $.each(options.Array_id, function (idx, val) {
                        Array_item.push(val);
                    });
                    jsonObj = eval(data);
                    var x = options.Array_id.length;
                    $.each(jsonObj, function (index, item) {
                        jsonData = eval(item);
                        switch (index) {
                            case "Record-0":
                                $.each(jsonData, function (idx, itm) {
                                    i = i + 1;
                                    $("#cont").append("<tr id=r-" + i + "></tr>");
                                    var s = eval(itm);
                                    var j = 1;
                                    $.each(s, function (ind, va) {
                                        if (j == 1) {
                                            $("#r-" + i).append("<td id='r-" + i + "-" + j + "'><input type='checkbox' lay-skin='primary' id=del-" + i + " Dataid=" + options.Array_id[0] + " Datavalue=" + va + " ></td>");
                                        }
                                        else {
                                              $("#r-" + i).append("<td id='r-" + i + "-" + j + "'Dataid=" + options.Array_id[j-1] + ">" + va + "</td>");
                                        }
                                        if (j == x) {
                                            $("#r-" + i).append("<td><button class='layui-btn layui-btn-mini' title='编辑' Dataid=" + options.Array_id[0] + " id='r-" + i + "-" + (x + 1) + "'  onclick=CJPlugin.buttonStatus('r-" + i + "-" + (x + 1) + "','r-" + i + "-" + (x + 2) + "','r-" + i + "-" + (x + 3) + "','r-" + i + "-" + (x + 4) + "','" + i + "','" + (x + 1) + "','" + options.editMode + "');>编辑</button>"
                                             + "<button class='layui-btn layui-btn-mini layui-btn-normal' title='更新' Dataid=" + options.Array_id[0] + " id='r-" + i + "-" + (x + 2) + "' onclick=CJPlugin.buttonStatus('r-" + i + "-" + (x + 1) + "','r-" + i + "-" + (x + 2) + "','r-" + i + "-" + (x + 3) + "','r-" + i + "-" + (x + 4) + "','" + i + "','" + (x + 1) + "','update','" + options.table + "');  style='display:none;'>更新</button>"
                                             + "<button class='layui-btn layui-btn-mini layui-btn-warm' title='取消' Dataid=" + options.Array_id[0] + " id='r-" + i + "-" + (x + 3) + "'  onclick=CJPlugin.buttonStatus('r-" + i + "-" + (x + 1) + "','r-" + i + "-" + (x + 2) + "','r-" + i + "-" + (x + 3) + "','r-" + i + "-" + (x + 4) + "','" + i + "','" + (x + 1) + "','cancel');  style='display:none;'>取消</button>"
                                             + "<button class='layui-btn layui-btn-mini layui-btn-danger' title='删除' Dataid=" + options.Array_id[0] + " id='r-" + i + "-" + (x + 4) + "'  onclick=CJPlugin.buttonStatus('r-" + i + "-" + (x + 1) + "','r-" + i + "-" + (x + 2) + "','r-" + i + "-" + (x + 3) + "','r-" + i + "-" + (x + 4) + "','" + i + "','" + (x + 1) + "','delete','" + options.table + "');>删除</button>"
                                             + "<button class='layui-btn layui-btn-mini layui-btn-primary' title='预览' id='r-" + i + "-" + (x + 5) + "' class='btn btn-xs btn-warning' onclick=''>预览</button></td>");
                                        }
                                        j++;
                                    })

                                })
                                break;
                            case "PageCount":
                                ///console.log(item);
                                //分页
                                var datanum = item == 0 ? 1 : item;
                                options.select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
                                options.pagecount = Math.ceil(parseInt(datanum) / options.select_row);
                                //page
                                laypage({
                                    cont: 'page',
                                    pages: options.pagecount,//总页数 
                                    groups: 3,//连续显示分页数
                                    skip: true, //是否开启跳页
                                    //skin: '#5FB878',
                                    curr: options.curr_num || 1, //当前页
                                    jump: function (obj, first) {
                                        //得到了当前页，用于向服务端请求对应数据                        
                                        if (!first) {
                                            options.curr = obj.curr;
                                            options.curr_num = obj.curr;
                                            plugin_api.GetValue();
                                        }
                                    }
                                });
                                break;
                            default: Array_item = []; break;
                        }

                    })
                    form.render('checkbox');
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        //console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                    }
                    //parent.layer.msg('加载失败', { icon: 2, time: 1000 });
                },
            });
        },
        //paging: function () {
        //    var sql = "select count(*) from " + options.table;
        //    $.ajax({
        //        type: 'get',
        //        url: options.page_url + "?t=" + Math.random().toString(),
        //        data: "sql=" + sql,
        //        dataType: 'text',
        //        cache: false,
        //        //async: false,
        //        beforeSend: function () {
        //            ///
        //        },
        //        success: function (data, textStatus) {
        //            var datanum = parseInt(data) == 0 ? data = 1 : data;
        //            options.select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
        //            options.pagecount = Math.ceil(parseInt(datanum) / options.select_row);
        //            //page
        //            laypage({
        //                cont: 'page',
        //                pages: options.pagecount,//总页数 
        //                groups: 3,//连续显示分页数
        //                skip: true, //是否开启跳页
        //                //skin: '#5FB878',
        //                curr: options.curr_num || 1, //当前页
        //                jump: function (obj, first) {
        //                    //得到了当前页，用于向服务端请求对应数据                        
        //                    if (!first) {
        //                        options.curr = obj.curr;
        //                        options.curr_num = obj.curr;
        //                        plugin_api.GetValue();
        //                    }
        //                }
        //            });
        //        },
        //        error: function (xhr) {
        //            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
        //                console.log(xhr);
        //                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
        //                return;
        //            }
        //        },
        //    });
        //},

        buttonStatus: function (edit_button, update_button, cancel_button, del_button, row, column, type, tableid) {
            options.tr_count = $("#cont tr").length;
            console.log(row);
            var a = 2, b = 2, c = 2, r = 0;
            switch (type) {
                case "edit_a":
                    if (document.getElementById("r-" + row + "-1").innerHTML != "") {//数据是否为空
                        console.log(edit_button);
                        $("#" + edit_button + "").css("display", "none");
                        $("#" + del_button + "").css("display", "none");
                        $("#" + update_button + "").css("display", "");
                        $("#" + cancel_button + "").css("display", "");
                        for (c; c < column; c++) {
                            if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                                var value = $("#r-" + row + "-" + c + "").html();
                                $("#r-" + row + "-" + c + "").empty();
                                $("#r-" + row + "-" + c + "").attr("Datavalue", value);
                                $("#r-" + row + "-" + c + "").append("<input style='width:80%;height:100%;' type='text' onchange=CJPlugin.setJson('" + row + "','" + $("#r-" + row + "-" + c + "").attr("Dataid") + "',this.value) style='width:90%;' value='" + $("#r-" + row + "-" + c + "").attr("Datavalue") + "'/>");
                            } else { break; }
                        }
                        if (options.original_row != row) {
                            for (a; a < column; a++) {
                                if (a != row) {
                                    $("#r-" + options.original_row + "-" + column + "").css("display", "");
                                    $("#r-" + options.original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                                    $("#r-" + options.original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                                    $("#r-" + options.original_row + "-" + (Number(column) + 3) + "").css("display", "");
                                }
                            }
                            for (b; b < column; b++) {
                                if ($("#r-" + row + "-" + b + "").attr("Dataid") != "time") {//时间字段不需要编辑
                                    $("#r-" + options.original_row + "-" + b + "").empty();
                                    $("#r-" + options.original_row + "-" + b + "").append($("#r-" + options.original_row + "-" + b + "").attr("Datavalue"));
                                } else { break; }
                            }
                            //纪录当前行
                            options.original_row = row;
                        }
                    }
                    else { parent.layer.msg('无数据', { icon: 2, time: 2000 }); }
                    break;
                case "edit_b":
                    var thNum = $('#' + options.Ctable).children('thead').find('tr th').length-1; //获取id为table的th对象(表格有多少列，取倒数第二列) 
                    if (document.getElementById("r-" + row + "-1").innerHTML != "") {//数据是否为空
                        
                        var index = parent.layer.open({
                            type: 2,
                            maxmin: true,
                            scrollbar: true,
                            shade: 0,
                            title: "编辑",
                            area: ['730px', '100%'],
                            //btn: ['火速围观', '残忍拒绝'],
                            //moveType: 1, //拖拽模式，0或者1
                            content: '/master/' + options.table + '-edit.html?id=' + $("#del-" + row).attr("datavalue") + '&file=' + $("#r-" + row + "-" + thNum).text(),
                            zIndex: layer.zIndex, //重点1
                            success: function (layero) {
                                parent.layer.setTop(layero); //重点2
                            }
                        });
                        //弹出即全屏
                        //parent.layer.full(index);
                    }
                    else { parent.layer.msg('无数据', { icon: 2, time: 2000 }); }
                    break;
                case "edit_c":
                    mid = $("#del-" + row).attr("datavalue");
                    parent.layer.open({
                        type: 2,
                        scrollbar: false,
                        shade: [0.2],
                        shadeClose: false,
                        area: ['460px', '450px'],
                        //btn: ['火速围观', '残忍拒绝'],
                        //moveType: 1, //拖拽模式，0或者1
                        content: '/master/edit-user.html?mid=' + mid + "&idx=" + row + "&idList=" + options.Array_id,

                    });
                    break;
                case "cancel":
                    for (r; r < options.tr_count; r++) {
                        $("#r-" + r + "-" + column + "").css("display", "");
                        $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                    }
                    for (c; c < column; c++) {
                        if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                            $("#r-" + row + "-" + c + "").empty();
                            $("#r-" + row + "-" + c + "").append($("#r-" + row + "-" + c + "").attr("Datavalue"));
                        } else { break; }
                    }
                    break;
                case "update":
                    //数据库操作
                    var sqlstring = null;
                    $.each(JsonData, function (idx, val) {//迭代jsondate 为空不执行。
                        sqlstring = "UPDATE " + tableid + " SET";
                        $.each(JsonData, function (name, value) {
                            sqlstring = sqlstring + " " + name + "='" + value + "',";
                        });
                    });
                    if (sqlstring != null) {
                        sqlstring = sqlstring.substring(0, sqlstring.length - 1) + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";
                        $.ajax({                                                  //调用jquery的ajax方法   
                            type: "POST",                                      //设置ajax方法提交数据的形式   
                            url: "handler/ExecuteHandler.ashx",                 //把数据提交到ashx  
                            //async: false,
                            data: "sql=" + sqlstring,     //输入框writer中的值作为提交的数据 
                            beforeSend: function () {

                            },
                            success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                                //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                                $("#" + edit_button + "").css("display", "");
                                $("#" + del_button + "").css("display", "");
                                $("#" + update_button + "").css("display", "none");
                                $("#" + cancel_button + "").css("display", "none");
                                for (r; r < options.tr_count; r++) {
                                    $("#r-" + r + "-" + column + "").css("display", "");
                                    $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                                    $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                                    $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                                }
                                for (c; c < column; c++) {
                                    if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                                        var value = $("#r-" + row + "-" + c + " input").val();
                                        $("#r-" + row + "-" + c).attr("Datavalue", value);
                                        $("#r-" + row + "-" + c + " input").remove();
                                        $("#r-" + row + "-" + c + "").append(value);
                                    } else { break; }
                                }
                                parent.layer.msg('处理成功', { icon: 1, time: 1000 });
                                JsonData = {};
                            },
                            error: function (xhr) {
                                if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                                    console.log(xhr);
                                    this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                                }
                                parent.layer.msg('处理失败', { icon: 2, time: 1000 });
                            },
                        });
                       
                        // }
                    }
                    else {
                        $("#" + edit_button + "").css("display", "");
                        $("#" + del_button + "").css("display", "");
                        $("#" + update_button + "").css("display", "none");
                        $("#" + cancel_button + "").css("display", "none");
                        for (r; r < options.tr_count; r++) {
                            $("#r-" + r + "-" + column + "").css("display", "");
                            $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                            $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                            $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                        }
                        for (c; c < column; c++) {
                            if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                                var value = $("#r-" + row + "-" + c + " input").val();
                                $("#r-" + row + "-" + c).attr("Datavalue", value);
                                $("#r-" + row + "-" + c + " input").remove();
                                $("#r-" + row + "-" + c + "").append(value);
                            } else { break; }
                        }
                        parent.layer.msg('数据没有变动', { icon: 4, time: 1000 });
                    }
                    break;
                case "delete":
                    if (document.getElementById("r-" + row + "-1").innerHTML != "&nbsp;") {//数据是否为空
                        //询问框
                        parent.layer.confirm('您是否要删除？', {
                            btn: ['是的', '算了'] //按钮
                        }, function () {
                            var sql = "delete from " + tableid + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";
                            $.ajax({                                                  //调用jquery的ajax方法   
                                type: "POST",                                      //设置ajax方法提交数据的形式   
                                url: "handler/ExecuteHandler.ashx",                 //把数据提交到ashx  
                                //async: false,
                                data: "sql=" + sql,     //输入框writer中的值作为提交的数据 
                                beforeSend: function () {

                                },
                                success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                                    //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                                    $("#r-" + row).remove();
                                    options.tr_count = $("#cont tr").length;
                                    if (options.tr_count == '0') {
                                        options.curr_num = options.curr_num - 1;
                                        options.curr = options.curr - 1;
                                        options.pagecount = options.pagecount - 1;
                                        plugin_api.GetValue();
                                        //setTimeout(plugin_api.paging(), "500");
                                    }
                                    parent.layer.msg('处理成功', { icon: 1, time: 1000 });
                                    JsonData = {};
                                },
                                error: function (xhr) {
                                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                                        console.log(xhr);
                                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                                    }
                                    parent.layer.msg('处理失败', { icon: 2, time: 1000 });
                                },
                            });

                            if (options.original_row != row) {
                                for (a; a < column; a++) {
                                    if (r != row) {
                                        $("#r-" + options.original_row + "-" + column + "").css("display", "");
                                        $("#r-" + options.original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                                        $("#r-" + options.original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                                        $("#r-" + options.original_row + "-" + (Number(column) + 3) + "").css("display", "");
                                    }
                                }
                                for (b; b < column; b++) {
                                    $("#r-" + options.original_row + "-" + b + "").empty();
                                    $("#r-" + options.original_row + "-" + b + "").append($("#r-" + options.original_row + "-" + b + "").attr("Datavalue"));
                                }
                            }

                        }, function () {
                            //layer.msg('取消', {
                            //    time: 20000, //20s后自动关闭
                            //    btn: ['明白了', '知道了']
                            //});
                        });
                    } else { layer.msg('无数据', { icon: 2, time: 2000 }); }
                    break;
                default:
                    //type 与 case 1 和 case 2 不同时执行的代码
            }

        },
        execute: function (table, value, type, filename, field_id) {
            var sql;
            switch(type)
            {
                case "insert":
                    sql = "insert into " + table + " (" + field_id + ")" + " values(" + value + ");"
                    break;
                case "update":
                    sql = "UPDATE " + table + " SET " + value + " WHERE id='"+field_id+"'";
                    console.log(sql);
                    break;
                case "delete":

                    break;
                default:
                   // n 与 case 1 和 case 2 不同时执行的代码
            }
            $.ajax({                                                  //调用jquery的ajax方法   
                type: "POST",                                      //设置ajax方法提交数据的形式   
                url: base + filename + ".ashx",                 //把数据提交到ashx  
                //async: false,
                data: {
                    "sql": sql
                },
                dataType: "json",
                beforeSend: function () {

                },
                success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                    //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                    parent.layer.msg("处理成功", { icon: 1, time: 1000 });
                    JsonData = {};
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        //console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                    }
                    //parent.layer.msg('处理失败', { icon: 2, time: 1000 });
                },
            });
        },
        setJson: function (row, name, value) {
            if (EditSingle != row && EditSingle > 0) {
                // 添加 或 修改
                JsonData = {};
                JsonData[name] = value;
                EditSingle = row;
            }
            else {
                // 添加 或 修改
                JsonData[name] = value;
                EditSingle = row;
            }
            console.log(JsonData);
        },
        deleteAll: function () {
            var deleteID = null, rowid = [];
            //options.tr_count = $("#cont tr").length;
            //获取所有选择的列
            $('#cont').children('tr').each(function (idx) {
                idx = parseInt(idx) + 1;
                var $that = $(this);
                var $cbx = $that.children('td').eq(0).children('input[type=checkbox]')[0].checked;
                if ($cbx) {
                    rowid.push("#r-" + idx);
                    if (deleteID == null) { deleteID = "'" + $("#del-" + idx).attr("datavalue") + "'"; }
                    else { deleteID = deleteID + ",'" + $("#del-" + idx).attr("datavalue") + "'"; }
                }
            });
            
            if (deleteID != null) {
                parent.layer.confirm('您是否要删除？', {
                    btn: ['是的', '算了'] //按钮
                }, function () {
                    var sql = "delete from " + options.table + " where " + $("#selected-all").attr("Dataid") + " in(" + deleteID + ");"
                    $.ajax({                                                  //调用jquery的ajax方法   
                        type: "POST",                                      //设置ajax方法提交数据的形式   
                        url: "handler/ExecuteHandler.ashx",                 //把数据提交到ashx  
                        //async: false,
                        data: "sql=" + sql,     //输入框writer中的值作为提交的数据 
                        beforeSend: function () {

                        },
                        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                            for (var i = 0; i < rowid.length; i++) {
                                $(rowid[i]).remove();
                            }
                            rowid = [];
                            options.tr_count = $("#cont tr").length;
                            if (options.tr_count == '0') {
                                options.curr_num = options.curr_num - 1;
                                options.curr = options.curr - 1;
                                options.pagecount = options.pagecount - 1;
                                plugin_api.GetValue();
                            }
                            parent.layer.msg('处理成功', { icon: 1, time: 1000 });
                            JsonData = {};
                        },
                        error: function (xhr) {
                            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                                console.log(xhr);
                                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                            }
                            parent.layer.msg('处理失败', { icon: 2, time: 1000 });
                        },
                    });
                }, function () {
                    //layer.msg('取消', {
                    //    time: 20000, //20s后自动关闭
                    //    btn: ['明白了', '知道了']
                    //});
                });
            }
            else { parent.layer.msg('请先选择要删除的数据！', { icon: 2, time: 2000 }); };
        },
        changeRow: function (row) {
            options.curr = '1';
            options.curr_num = '1';
            if (localStorage.rowlength) { localStorage.rowlength = row; } else { $("#select_row").val("10"); localStorage.rowlength = "10"; }
            plugin_api.GetValue();
            //plugin_api.paging();
            
        },
        //添加分类
        addClassRecord: function (v, table) {
            v = "insert into " + table + " values(" + v + ");";
            $.ajax({                                                  //调用jquery的ajax方法   
                type: "POST",                                      //设置ajax方法提交数据的形式   
                url: "handler/ListHTMLhandler.ashx",                                       //把数据提交到ashx  
                data: {
                    "sql": v,
                    "table": table
                },
                dataType: "json",
                beforeSend: function () {
                },
                success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                    //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                     layer.msg('处理成功', { icon: 1, time: 2000 });
                    // if (table != null) { create(table); }
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                    }
                    //layer.msg('处理失败', { icon: 2, time: 2000 });
                },
            });
        },
        initKindEditor: function (Editor_div, button, Gridly_div) {
            KindEditor.ready(function (K) {
                editor = K.create('#'+Editor_div, {
                    cssPath: 'kindeditor/plugins/code/prettify.css',
                    uploadJson: 'kindeditor/upload_json.ashx',
                    fileManagerJson: 'kindeditor/file_manager_json.ashx',
                    resizeType: 1,//不能拖动大小
                    height:"370px",
                    allowFileManager: true,
                    afterCreate: function () {
                        var self = this;
                        self.sync();
                    },
                    //同步KindEditor值
                    afterBlur: function () { this.sync(); }
                });

                K('#' + button).click(function () {
                    editor.loadPlugin('multiimage', function () {
                        editor.plugin.multiImageDialog({
                            clickFn: function (urlList) {
                                var div = K('.' + Gridly_div);
                                div.html('');
                                var count = $('.'+Gridly_div).find("div").length;
                                K.each(urlList, function (i, data) {
                                    div.append('<div class="brick small" id=' + Number(i + count) + ' style="position: absolute; left: 0px; top: 0px;"><img index=' + Number(i + count) + ' name="p' + Number(i + count) + '" width="120px" height="120px" src=' + data.url + ' ondblclick="CJPlugin.show(this.name);" alt="" /><a class="delete" href="#">×</a></div>')
                                });
                                //生成json  arr[i].id排序索引  
                                editor.hideDialog();
                                $('.gridly').gridly();
                                $.initPicJson.init("gridly");
                            }
                        });
                    });
                });
                prettyPrint();
            });
        },
        reLoad: function () {
            var row_count = $("#cont tr").length;
            if (row_count == '0') {
                options.curr_num = options.curr_num - 1;
            } else {
                // CJPlugin.init.
                options.curr_num = $(".layui-laypage-curr").text();
            }
            plugin_api.GetValue();
        },
        openWindow: function (type, maxmin, scrollbar, shade, title, area, shadeClose, closeBtn, url, fullscr) {
            var index = parent.layer.open({
                type: type || 1,
                maxmin: maxmin || false,
                scrollbar: scrollbar || false,
                shade: shade || 0,
                title: title || false,
                area: area || 'auto',
                shadeClose: shadeClose || false,
                closeBtn: closeBtn || 0,
                //btn: ['火速围观', '残忍拒绝'],
                //moveType: 1, //拖拽模式，0或者1
                content: "/master/" + url + ".html",
                zIndex: layer.zIndex, //重点1
                success: function (layero) {
                    parent.layer.setTop(layero); //重点2
                }
            });
            if (fullscr) { parent.layer.full(index); }
        },
        imageInsert: function () {
            console.log("图片插入中。。。");
        },
        addPhotoClass: function () {
            var v = $("#addvalue").val();
            var d = new Date();
            var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();

            if (v && table != "galleryclass") {
                plugin_api.execute("insert into " + table + " values('" + uuid(6, 16) + "','" + $("#addvalue").val() + "','" + t + "','" + table + "');", table);

            } else {
                plugin_api.execute("insert into " + table + " values('" + uuid(6, 16) + "','" + $("#addvalue").val() + "','" + t + "');", null);
            }
        },
        loadClass: function (container, url,Array_id, table) {
            var sql = "select " + Array_id + " from " + table + " order by time desc";
            var tmp = Math.random().toString();
            $.ajax({
                type: 'POST',
                url: base+url +"?t="+ tmp,
                data: {
                    "sql": sql
                },
                dataType: 'json',
                cache: false,
                beforeSend: function () {
                    //dialogID = layer.load(2, { shade: [0.1, '#fff'] });
                },
                success: function (data, textStatus) {
                    //layer.close(dialogID);
                    var jsonData = eval(data);
                    //var jsonObj = eval('(' + data + ')');
                    console.log(data);
                    var Array_item = [];
                    rowCount = jsonData.length;
                    if ($("#" + container)) {
                        $.each(jsonData, function (index, objVal) { //遍历对象数组，index是数组的索引号，objVal是遍历的一个对象。objVal["属性"]可取到对应的属性值。 
                            //console.log(objVal);
                            $("#" + container).append("<option value='" + objVal["classname"] + "'>" + objVal["classname"] + "</option")
                            //$.each(Array_id, function (idx, val) {
                            //    Array_item.push(objVal[val]);
                            //});
                            //Array_item = [];
                        });
                    }
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                        return;
                    }
                    layer.close(dialogID);
                    layer.msg('加载失败', { icon: 1, time: 2000 });
                    return;
                },

            });
        },
        addalt: function () {
            $("img[name='" + _name + "']").prop("alt", $("#alttext").val());
            $.setPicJson.create("gridly", _arr);
            layer.close(index);
        },
        show: function(name) {
        _name = name;
        index = layer.open({
            type: 1,
            title: false,
            area: ['300px', '188px'],
            skin: '',
            closeBtn: 0,
            shadeClose: true,
            scrollbar: false,
            content: '<div align="center"><textarea id="alttext" style="width:98%;height:160px;resize:none;background:transparent;border-style:none;">' + $("img[name='" + _name + "']").prop("alt") + '</textarea><input class="am-btn am-btn-primary am-btn-xs" type="button" value="确定" onclick="CJPlugin.addalt();"/></div>'
        });
        },
        bind: function (id, pkey, tableA, filename, field_idA, controlId, field_idB, tableB) {
            var sql1 = "select " + field_idA + " from " + tableA + " where " + pkey + "='" + id + "'";
            var sql2 = "select " + field_idB + " from " + tableB;
            var tmp = Math.random().toString();
            $.ajax({
                type: 'POST',
                url: base + filename + ".ashx?t=" + tmp,
                data: {
                    "sql1": sql1,
                    "sql2": sql2
                },
                dataType: 'json',
                cache: false,
                beforeSend: function () {
                    //dialogID = layer.load();
                },
                success: function (data, textStatus) {
                    //layer.close(dialogID);
                    var jsonObj = eval(data);
                    var i = 0;
                    var cname = null;
                    $.each(jsonObj, function (index, objVal) {
                        switch (index) {
                            case "Record-0":
                                $.each(objVal[0], function (_index, _objVal) {
                                    var c = controlId[i];
                                    var item = $("#" + c);
                                    var str = null;
                                    var num = 1;
                                    if (c != "content1" && c != "classname" && c != "gridly" && c != "state") {
                                        item.val(_objVal);
                                    } else if (c == "content1") {
                                        editor.html(_objVal);
                                    } else if (c == "classname") {
                                        //设置分类选中
                                        cname = _objVal;
                                    } else if (c == "gridly") {

                                        item.html('');
                                        var parentJson = eval('(' + _objVal + ')');// 多维json 需要加（''）
                                        $("#imagelist").val(parentJson);
                                        //console.log(parentJson);
                                        $.each(parentJson, function (parent_index, parent_value) {
                                            var childJson = eval(parent_value);
                                            $.each(childJson, function (child_indx, child_value) {
                                                if (num == 1) {
                                                    str = "<div class='brick small' id='" + child_value + "'style='position: absolute; left: 0px; top: 0px;'><img index='" + child_value + "' name='p" + child_value + "' width='120px' height='120px' ";
                                                    num = num + 1;
                                                }
                                                else if (num == 2) { str = str + "src='" + child_value + "' ondblclick='show(this.name);' "; num = num + 1; }
                                                else if (num == 3) { str = str + "alt='" + child_value + "' /><a class='delete' href='#'>×</a></div>"; num = 1; }
                                            });
                                            item.append(str);
                                        });
                                        $('.gridly').gridly();
                                        $.initPicJson.init("gridly");
                                    } else if (c == "state") {
                                        obj = $("input[name='" + c + "']");
                                        _objVal == "True" ? obj.eq(0).attr("checked", _objVal) : obj.eq(1).attr("checked", _objVal);
                                    }
                                    i++;
                                });
                                break;
                            case "Record-1":
                                $.each(objVal, function (_index, _objVal) {
                                    $("#classname").append("<option value='" + _objVal["classname"] + "'>" + _objVal["classname"] + "</option");
                                });
                                $("#classname").val(cname);
                                break;
                            default: break;
                        }
                   });
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        //console.log(xhr);
                        //this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                        return;
                    }
                    return;
                },

            });
        }
        ,
        getTime: function () {
            var time = new Date();
            // 程序计时的月从0开始取值后+1
            var m = time.getMonth() + 1;
            var t = time.getFullYear() + "-" + m + "-"
              + time.getDate() + " " + time.getHours() + ":"
              + time.getMinutes() + ":" + time.getSeconds();
            return t;
        }
    }
    //这里确定了插件的名称
    this.CJPlugin = plugin_api;
})(jQuery);

//url截取
jQuery.GetQueryString = {
    Get: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
}

    //adduser:function(tableid) {
    //    $("#addbtn").attr("disabled", "disabled");
    //    $("#addbtn").attr('value', "loading");
    //    setTimeout(function () {
    //        $("#addbtn").attr('value', "添加");
    //        $("#addbtn").removeAttr("disabled");
    //    }, 2000);
    //    var d = new Date();
    //    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    //    var value = "'" + uuid(8, 16) + "','" + $("#username").val() + "','" + $("#password").val() + "','" + $("#email").val() + "','" + t + "'";
    //    var sqlstring = "insert into " + tableid + " values(" + value + ");"
    //    execute(sqlstring)
    //},





